package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.api.UserApi;
import com.example.mydy.model.Task;
import com.example.mydy.model.TaskListResponse;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.utils.CacheUtils;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.MockDataManager;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TaskActivity extends AppCompatActivity implements TaskAdapter.OnTaskClickListener {
    private static final String TAG = "TaskActivity";
    private static final int REQUEST_CODE_PICK_IMAGE = 1001;
    
    private EditText etTaskTitle;
    private EditText etTaskLink;
    private EditText etTaskContent;
    private Button btnSelectImage;
    private TextView tvSelectedImage;
    private ImageView ivTaskImagePreview;
    private Button btnSubmitTask;
    private TextView tvBalance;
    private RecyclerView rvTasks;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TaskAdapter taskAdapter;
    private List<Task> taskList = new ArrayList<>();
    
    private Uri selectedImageUri = null;
    
    private SharedPreferences prefs;
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_BALANCE = "balance";
    private static final String KEY_USERNAME = "username";
    
    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);

        // 初始化Shared Preferences和API服务
        prefs = ((MyDyApplication) getApplicationContext()).getSecureSharedPreferences();
        userApi = NetworkUtils.getUserApi();
        
        // 初始化视图
        initViews();
        setupRecyclerView();
        setupSwipeRefresh();
        setupImagePicker();
        setupSubmitButton();
        
        // 加载任务列表
        loadTasks();
        
        // 更新余额显示
        float balance = Float.parseFloat(prefs.getString(KEY_BALANCE, "0"));
        tvBalance.setText(String.format("余额：%.2f", balance));
    }

    private void initViews() {
        etTaskTitle = findViewById(R.id.et_task_title);
        etTaskLink = findViewById(R.id.et_task_link);
        etTaskContent = findViewById(R.id.et_task_content);
        btnSelectImage = findViewById(R.id.btn_select_image);
        tvSelectedImage = findViewById(R.id.tv_selected_image);
        ivTaskImagePreview = findViewById(R.id.iv_task_image_preview);
        btnSubmitTask = findViewById(R.id.btn_submit_task);
        tvBalance = findViewById(R.id.tv_balance);
        rvTasks = findViewById(R.id.rv_tasks);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
    }
    
    private void setupRecyclerView() {
        taskAdapter = new TaskAdapter(taskList, this);
        rvTasks.setLayoutManager(new LinearLayoutManager(this));
        rvTasks.setAdapter(taskAdapter);
    }
    
    private void setupSwipeRefresh() {
        swipeRefreshLayout.setOnRefreshListener(this::loadTasks);
    }
    
    private void setupImagePicker() {
        btnSelectImage.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_CODE_PICK_IMAGE);
        });
    }
    
    private void setupSubmitButton() {
        btnSubmitTask.setOnClickListener(v -> submitTask());
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                // 显示选中的图片文件名
                String fileName = ImageUtils.getFileNameFromUri(this, selectedImageUri);
                tvSelectedImage.setText(fileName);
                
                try {
                    // 显示图片预览
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                    ivTaskImagePreview.setImageBitmap(bitmap);
                    ivTaskImagePreview.setVisibility(View.VISIBLE);
                } catch (IOException e) {
                    Log.e(TAG, "加载图片预览失败", e);
                    Toast.makeText(this, "加载图片预览失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    private void loadTasks() {
        // 显示加载指示器
        if (!swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(true);
        }
        
        // 如果是离线模式，从MockDataManager加载数据
        if (NetworkUtils.USE_OFFLINE_MODE) {
            Log.d(TAG, "离线模式：从MockDataManager加载任务");
            taskList.clear();
            
            // 获取用户名
            String username = prefs.getString(KEY_USERNAME, "");
            if (!TextUtils.isEmpty(username)) {
                // 从MockDataManager获取任务
                List<Task> mockTasks = MockDataManager.getUserTasks(username);
                if (mockTasks != null && !mockTasks.isEmpty()) {
                    taskList.addAll(mockTasks);
                    Log.d(TAG, "从MockDataManager加载了 " + mockTasks.size() + " 个任务");
                } else {
                    Log.d(TAG, "MockDataManager中没有找到任务");
                }
            } else {
                Log.e(TAG, "用户名为空，无法加载任务");
            }
            
            taskAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);
            return;
        }
        
        // 从API获取任务列表
        if (NetworkUtils.isNetworkConnected(this)) {
            String token = NetworkUtils.getAuthToken(this);
            if (token != null && !token.isEmpty()) {
                userApi.getUserTasks("Bearer " + token).enqueue(new Callback<TaskListResponse>() {
                    @Override
                    public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            // 更新任务列表
                            taskList.clear();
                            if (response.body().getTasks() != null && !response.body().getTasks().isEmpty()) {
                                taskList.addAll(response.body().getTasks());
                            }
                            taskAdapter.notifyDataSetChanged();
                            Log.d(TAG, "成功加载 " + taskList.size() + " 个任务");
                            
                            // 缓存任务数据
                            CacheUtils.cacheTasks(TaskActivity.this, taskList);
                        } else {
                            // 加载失败，显示错误信息
                            String errorMsg = response.isSuccessful() && response.body() != null ? 
                                    response.body().getMessage() : "加载任务失败";
                            Toast.makeText(TaskActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "加载任务失败: " + errorMsg);
                            
                            // 加载本地缓存的任务
                            loadCachedTasks();
                        }
                        
                        // 停止刷新动画
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    
                    @Override
                    public void onFailure(Call<TaskListResponse> call, Throwable t) {
                        // 网络请求失败，显示错误信息
                        Toast.makeText(TaskActivity.this, "加载任务失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "加载任务网络错误", t);
                        
                        // 加载本地缓存的任务
                        loadCachedTasks();
                        
                        // 停止刷新动画
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            } else {
                // 令牌为空，加载本地缓存
                loadCachedTasks();
                swipeRefreshLayout.setRefreshing(false);
            }
        } else {
            // 无网络连接，加载本地缓存
            Toast.makeText(this, "无网络连接，显示缓存数据", Toast.LENGTH_SHORT).show();
            loadCachedTasks();
            swipeRefreshLayout.setRefreshing(false);
        }
    }
    
    /**
     * 从缓存加载任务数据
     */
    private void loadCachedTasks() {
        // 加载本地缓存的任务数据
        taskList.clear();
        
        // 尝试从缓存获取任务
        List<Task> cachedTasks = CacheUtils.getCachedTasks(this);
        if (cachedTasks != null && !cachedTasks.isEmpty()) {
            taskList.addAll(cachedTasks);
            taskAdapter.notifyDataSetChanged();
            Log.d(TAG, "从缓存加载 " + cachedTasks.size() + " 个任务");
        } else {
            Log.d(TAG, "缓存中没有任务数据");
        }
    }
    
    private void submitTask() {
        String title = etTaskTitle.getText().toString().trim();
        String link = etTaskLink.getText().toString().trim();
        String content = etTaskContent.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (link.isEmpty() && content.isEmpty()) {
            Toast.makeText(this, "请输入任务链接或内容描述", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示提交中
        btnSubmitTask.setEnabled(false);
        btnSubmitTask.setText("提交中...");
        
        // 获取认证令牌
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "用户未登录，请先登录", Toast.LENGTH_SHORT).show();
            btnSubmitTask.setEnabled(true);
            btnSubmitTask.setText("提交任务");
            return;
        }
        
        // 离线模式处理
        if (NetworkUtils.USE_OFFLINE_MODE) {
            String username = prefs.getString(KEY_USERNAME, "");
            if (TextUtils.isEmpty(username)) {
                Toast.makeText(this, "用户未登录，请先登录", Toast.LENGTH_SHORT).show();
                btnSubmitTask.setEnabled(true);
                btnSubmitTask.setText("提交任务");
                return;
            }
            
            // 创建任务对象
            Task task = new Task();
            task.setId((int)(System.currentTimeMillis() % Integer.MAX_VALUE)); // 使用时间戳作为ID并转换为int
            task.setTitle(title);
            task.setLink(link);
            task.setContent(content);
            task.setStatus("pending");
            task.setUsername(username); // 使用setUsername代替不存在的setCreatedBy
            task.setCreatedAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            
            // 使用MockDataManager提交任务
            boolean success = MockDataManager.getInstance().submitTask(task);
            
            if (success) {
                Toast.makeText(this, "任务提交成功（离线模式）", Toast.LENGTH_SHORT).show();
                clearForm();
                loadTasks(); // 重新加载任务列表
            } else {
                Toast.makeText(this, "任务提交失败", Toast.LENGTH_SHORT).show();
            }
            
            btnSubmitTask.setEnabled(true);
            btnSubmitTask.setText("提交任务");
            return;
        }
        
        // 创建提交数据
        if (selectedImageUri != null) {
            // 如果选择了图片，使用multipart表单提交
            submitTaskWithImage(token, title, link, content);
        } else {
            // 如果没有选择图片，使用普通表单提交
            submitTaskWithoutImage(token, title, link, content);
        }
    }
    
    private void submitTaskWithoutImage(String token, String title, String link, String content) {
        Map<String, String> taskData = new HashMap<>();
        taskData.put("title", title);
        taskData.put("link", link);
        taskData.put("content", content);
        
        userApi.submitTask("Bearer " + token, taskData).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(TaskActivity.this, "任务提交成功", Toast.LENGTH_SHORT).show();
                        clearForm();
                        loadTasks(); // 重新加载任务列表
                    } else {
                        String errorMsg = response.body().getMessage();
                        if (TextUtils.isEmpty(errorMsg)) {
                            errorMsg = "任务提交失败";
                        }
                        Toast.makeText(TaskActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskActivity.this, "任务提交失败", Toast.LENGTH_SHORT).show();
                }
                
                btnSubmitTask.setEnabled(true);
                btnSubmitTask.setText("提交任务");
            }
            
            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskActivity.this, "任务提交失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG, "任务提交网络错误", t);
                
                btnSubmitTask.setEnabled(true);
                btnSubmitTask.setText("提交任务");
            }
        });
    }
    
    private void submitTaskWithImage(String token, String title, String link, String content) {
        try {
            // 准备图片文件
            File imageFile = ImageUtils.getFileFromUri(this, selectedImageUri);
            if (imageFile == null) {
                Toast.makeText(this, "无法读取选中的图片", Toast.LENGTH_SHORT).show();
                btnSubmitTask.setEnabled(true);
                btnSubmitTask.setText("提交任务");
                return;
            }
            
            // 创建multipart表单数据
            RequestBody titlePart = RequestBody.create(MediaType.parse("text/plain"), title);
            RequestBody linkPart = RequestBody.create(MediaType.parse("text/plain"), link);
            RequestBody contentPart = RequestBody.create(MediaType.parse("text/plain"), content);
            
            // 创建图片部分
            RequestBody imageRequestBody = RequestBody.create(MediaType.parse("image/*"), imageFile);
            MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", imageFile.getName(), imageRequestBody);
            
            // 发送请求
            userApi.submitTaskWithImage("Bearer " + token, titlePart, linkPart, contentPart, imagePart).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        if (response.body().isSuccess()) {
                            Toast.makeText(TaskActivity.this, "任务提交成功", Toast.LENGTH_SHORT).show();
                            clearForm();
                            loadTasks(); // 重新加载任务列表
                        } else {
                            String errorMsg = response.body().getMessage();
                            if (TextUtils.isEmpty(errorMsg)) {
                                errorMsg = "任务提交失败";
                            }
                            Toast.makeText(TaskActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(TaskActivity.this, "任务提交失败", Toast.LENGTH_SHORT).show();
                    }
                    
                    btnSubmitTask.setEnabled(true);
                    btnSubmitTask.setText("提交任务");
                }
                
                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Toast.makeText(TaskActivity.this, "任务提交失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "任务提交网络错误", t);
                    
                    btnSubmitTask.setEnabled(true);
                    btnSubmitTask.setText("提交任务");
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "提交任务时出现异常", e);
            Toast.makeText(this, "提交任务时出现异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            
            btnSubmitTask.setEnabled(true);
            btnSubmitTask.setText("提交任务");
        }
    }
    
    private void clearForm() {
        etTaskTitle.setText("");
        etTaskLink.setText("");
        etTaskContent.setText("");
        selectedImageUri = null;
        tvSelectedImage.setText("未选择图片");
        ivTaskImagePreview.setVisibility(View.GONE);
    }

    @Override
    public void onTaskClick(Task task) {
        // 打开任务详情页面
        Intent intent = new Intent(this, TaskDetailActivity.class);
        intent.putExtra("task_id", task.getId());
        startActivity(intent);
    }
}